package com.zghhost.codedemo.concurrent.threadpool;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.zghhost.codedemo.util.RuntimeUtil;

import java.util.concurrent.*;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/4/12 14:05
 */
public class ThreadPoolTest {
    private static ThreadFactory ntf = new ThreadFactoryBuilder()
            .setNameFormat("test-pool-%d").build();

    private static ExecutorService pool;

    public static void main(String[] args)throws Exception{
        watchMem();
        case0();
    }

    public static void watchMem(){
        new Thread(()->{
           while (true){
               if(pool != null && pool.isTerminated()){
                   break;
               }
               try{
                   Thread.sleep(1000);
               }catch (Exception e){}
               System.out.printf(
                       "%s %s %s \n"
                       ,"当前系统总内存"+ RuntimeUtil.getTotalMemory()
                       ,"当前系统最大内存"+ RuntimeUtil.getMaxMemory()
                       ,"当前系统空闲内存"+ RuntimeUtil.getFreeMemory()
               );
           }
        }).start();
    }

    public static void workWithPool(ExecutorService pool){
        ThreadPoolTest.pool = pool;
        try{
            for(int i=0,ic=1000000000;i<ic;i++){
                Thread.sleep(1);
                pool.execute(()->{
                    try{
                        //每个工作耗时十秒
                        Thread.sleep(1);
                        System.out.println(Thread.currentThread().getName());
                    }catch (Exception e){
                    }
                });
            }
            System.out.println("已经全部交给Execute运行");
            System.out.println(JSONObject.toJSONString(pool));
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("添加任务出现异常");
            JSONObject job = JSONObject.parseObject(JSON.toJSONString(pool));
            job.remove("queue");
            System.out.println(job.toString());
        }finally {
            pool.shutdown();
        }
    }

    public static void case0(){
//        ExecutorService pool = Executors.newFixedThreadPool(5,ntf);
//        ExecutorService pool = Executors.newCachedThreadPool(ntf);
//        ExecutorService pool = Executors.newScheduledThreadPool(5,ntf);
//        ExecutorService pool = Executors.newSingleThreadExecutor(ntf);
//        ExecutorService pool = new ThreadPoolExecutor(100, 200,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024), ntf, new ThreadPoolExecutor.AbortPolicy());
        ExecutorService pool = new ThreadPoolExecutor(100, 200,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024), ntf, new ThreadPoolExecutor.AbortPolicy());
        workWithPool(pool);
    }
}
